<!--
 * @Author: meixianming
 * @Date: 2022-11-16 11:22:36
 * @LastEditors: meixianming
 * @LastEditTime: 2022-11-16 19:55:28
 * @Description: 表单构建-电子签名封装
 * @FilePath: /front-end-of-task-center/src/components/generator/form-extention/un-d-esign/index.vue
-->
<template>
  <div class="un-esign-wrap">
    <div v-if="!isDisabled" class="un-esign">
      <vue-esign
        ref="esign"
        :width="width"
        :height="height"
        :lineWidth="lineWidth"
        :lineColor="lineColor"
        :bgColor="bgColor"
      />
      <div class="un-esign-btns">
        <el-button
          type="danger"
          small
          icon="el-icon-delete"
          circle
          title="清空画布"
          @click="handleClear"
        ></el-button>
        <el-button
          type="success"
          small
          icon="el-icon-check"
          circle
          title="确定签名"
          @click="handleUpload"
        ></el-button>
      </div>
    </div>
    <el-image v-else :src="value" fit="fill" :lazy="true"></el-image>
  </div>
</template>

<script>
import vueEsign from "vue-esign";
import emitter from "element-ui/lib/mixins/emitter";
import { getUsername } from "@/utils/auth";
import { postFileUpload } from "@/api/infra/file";

export default {
  name: "UnDEsign",
  components: { vueEsign },
  mixins: [emitter],
  props: {
    width: {
      type: Number,
      default: 800,
    },
    height: {
      type: Number,
      default: 200,
    },
    lineWidth: {
      type: Number,
      default: 4,
    },
    lineColor: {
      type: String,
      default: "#000000",
    },
    /* 是否禁用 */
    disabled: {
      type: Boolean,
      default: false,
    },
    bgColor: {
      type: String,
      default: "#ffffff",
    },
    /* saveEsign: {
      type: Function,
    }, */
    value: String,
  },
  inject: {
    elForm: {
      default: "",
    },
    elFormItem: {
      default: "",
    },
  },
  data() {
    return {
      fileList: [],
    };
  },
  computed: {
    isDisabled() {
      return this.disabled || !!(this.elForm || {}).disabled;
    },
  },
  watch: {
    value(value) {
      this.dispatch("ElFormItem", "el.form.change", value ? [value] : []);
    },
  },
  methods: {
    handleClear() {
      this.$refs.esign.reset();
    },
    handleUpload() {
      this.$refs.esign
        .generate()
        .then((res) => {
          let formData = new FormData();
          formData.append(
            "file",
            this.base64ToBlob(res),
            `${getUsername()}-esign-${new Date().getTime()}.png`
          );
          postFileUpload(formData).then((_res) => {
            if (_res.code === 0) {
              this.$message({
                message: "签名保存成功",
                type: "success",
              });
              // this.saveEsign(_res.data);
              this.$emit("input", _res.data);
            }
          });
        })
        .catch((err) => {
          this.$message.error("签名不能为空");
        });
    },
    base64ToBlob(urlData, type) {
      let arr = urlData.split(",");
      let mime = arr[0].match(/:(.*?);/)[1] || type;
      // 去掉url的头，并转化为byte
      let bytes = window.atob(arr[1]);
      // 处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length);
      // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
      let ia = new Uint8Array(ab);
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], {
        type: mime,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.un-esign-wrap {
  width: 100%;
  border: 1px solid #dbdfe6;
  border-radius: 5px;
}
.un-esign {
  position: relative;
  .un-esign-btns {
    position: absolute;
    right: 0px;
    top: 10px;
  }
}
</style>
